//
//  UIView+YLBase.m
//  YLBase
//
//  Created by simpletour on 30/09/2017.
//  Copyright © 2017 YL. All rights reserved.
//

#import "UIView+YLBase.h"
#import "YLHook.h"
#import <objc/runtime.h>

@implementation UIView (YLBase)

+(void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [YLHook hookWithClass:UIView.class originalSelector:@selector(initWithFrame:) swizzledSelector:@selector(yl_initWithFrame:)];
    });
}

-(instancetype)yl_initWithFrame:(CGRect)frame {
    id obj = [self yl_initWithFrame:frame];
    [self initialization];
    return obj;
}

//初始化方法调用
-(void)initialization {
    if(![NSStringFromClass(self.class) hasPrefix:@"UI"]) { //带UI开头的类都不实例化子属性
        [self initProperties];
    }
    [self before];
    [self addSubViews];
    [self layout];
    [self useStyle];
    [self after];
}

//初始化本类所有的UI属性
-(void)initProperties {
    unsigned int numIvars = 0;
    Ivar * ivars = class_copyIvarList(self.class, &numIvars);
    for(int i = 0; i < numIvars; i++) {
        Ivar thisIvar = ivars[i];
        const char *name = ivar_getName(thisIvar);
        const char *type = ivar_getTypeEncoding(thisIvar);
        NSString *stringName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        NSString *stringType =  [NSString stringWithCString:type encoding:NSUTF8StringEncoding];
        NSString *clazzType = [self classNameWithString:stringType];
        Class clazz = NSClassFromString(clazzType);
        if ([[self ignoreClasses] containsObject:clazz] | [[self ignoreViewNames] containsObject:stringName] || ![clazz isSubclassOfClass:UIView.class]) continue;
        id obj = [[clazz alloc]init];
        if ([stringType hasPrefix:@"@"] && [obj isKindOfClass:[UIView class]]) {
            object_setIvar(self, thisIvar, obj);
        }
    }
    free(ivars);
}

//规范类名
-(NSString *)classNameWithString:(NSString *)className {
    className = [className stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    NSString* str = [className stringByReplacingOccurrencesOfString:@"@" withString:@""];
    return str;
}

//忽略的类
-(NSArray<Class> *)ignoreClasses {
    return @[UICollectionView.class];
}

//忽略的UI属性
-(NSArray<NSString *> *)ignoreViewNames {
    return @[];
}

-(void)before{}
-(void)addSubViews{}
-(void)layout{}
-(void)useStyle{}
-(void)after{}

@end
